package org.chengyi.model_shop.mapper;

import org.apache.ibatis.annotations.*;

import org.chengyi.model_shop.entity.Order;
import org.chengyi.model_shop.entity.OrderItem;
import org.chengyi.model_shop.entity.OrderDetailDTO;
import org.chengyi.model_shop.entity.AdminOrderDetailDTO;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Update;

import java.util.List;

@Mapper
public interface OrderMapper {
    @Insert("INSERT INTO m_order (user_id, total_amount, status, created_at, address) VALUES (#{userId}, #{totalAmount}, #{status}, #{createdAt}, #{address})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int addOrder(Order order);
    @Insert("insert into order_item(order_id, product_id, quantity, price) values (#{orderId},#{productId},#{quantity},#{price})")
    int addOrderItem(OrderItem orderItem);
    
    // 查询用户订单详情
    List<OrderDetailDTO> selectOrderItmByUserId(Integer userId);
    
    // 更新订单状态
    @Update("UPDATE m_order SET status = #{status} WHERE id = #{orderId}")
    int updateOrderStatus(@Param("orderId") Integer orderId, @Param("status") Integer status);

    // 查询所有订单（用于后台管理）
    List<AdminOrderDetailDTO> selectAllAdminOrders();

    @Select("SELECT COUNT(*) FROM order_item WHERE product_id = #{productId}")
    int countOrderItemByProductId(@Param("productId") Integer productId);

    @Select("SELECT COUNT(*) FROM m_order WHERE user_id = #{userId}")
    int countOrderByUserId(@Param("userId") Integer userId);

    @Select("SELECT " +
            "o.id AS orderId, o.created_at AS createdAt, o.status, o.total_amount AS totalAmount, " +
            "o.user_id AS userId, u.username, " +
            "oi.product_id AS productId, oi.quantity, oi.price AS itemPrice, " +
            "p.name AS productName, p.image_url AS imageUrl " +
            "FROM m_order o " +
            "JOIN user u ON o.user_id = u.id " +
            "JOIN order_item oi ON o.id = oi.order_id " +
            "JOIN product p ON oi.product_id = p.id " +
            "WHERE u.username = #{username} " +
            "ORDER BY o.created_at DESC, o.id, oi.id")
    List<AdminOrderDetailDTO> getOrderListByUserName(String username);
}
